import router from './router'
import cache from './utils/cache'
// stores
import useUserStore from '@/stores/user'
// others
import { useTitle } from '@vueuse/core'
// 引入NProgress进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

router.beforeEach(async (to, from, next) => {
  // 进度条
  NProgress.start()

  const userInfo = cache.get('userInfo')
  const { setUserInfo } = useUserStore()
  setUserInfo(userInfo)

  const {
    meta: { title },
    matched
  } = to ?? {}

  console.log('matched', matched, userInfo)

  if (matched.length === 0) {
    next({ name: '404' })
    return
  }
  // 设置浏览器标题
  useTitle(title ? `${title}-云小账` : '云小账')
  if (userInfo && Object.keys(userInfo).length) {
    if (to.name === 'login') {
      next({ name: 'home' })
    } else {
      next()
    }
  } else {
    if (to.name === 'login') {
      next()
    } else {
      next({ name: 'login' })
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
